package com.ddc.study.feature.main.home;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ddc.study.R;
import com.ddc.study.base.TabReselectFragment;
import com.ddc.study.entity.Article;
import com.ddc.study.entity.Banner;
import com.ddc.study.entity.MainData;
import com.ddc.study.feature.collect.CollectActivity;
import com.ddc.study.feature.html.HtmlActivity;
import com.ddc.study.feature.login.LoginActivity;
import com.ddc.study.user.UserManager;
import com.ddc.study.util.Log;
import com.ddc.study.view.CyclicViewPager;
import com.google.android.material.appbar.AppBarLayout;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;

/**
 * Created on 2018/5/21.
 *
 * @author lshun
 * @version 1.0
 */
public class HomeFragment extends TabReselectFragment<HomeContract.IView, HomeContract.IPresenter>
        implements HomeContract.IView {
    private static final int REQUEST_CODE_LOGIN = 0x01;
    private static final int REQUEST_CODE_COLLECT = 0x02;

    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;

    @BindView(R.id.cyclic_view_pager)
    CyclicViewPager mCyclicViewPager;

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private HomeAdapter mAdapter;
    private int mPage;

    private List<Banner> mBannerList;

    private UserManager.UserObserver mUserObserver;

    @Override
    protected int getLayoutRes() {
        return R.layout.frag_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserObserver = user -> {
            //是否需要刷新RecyclerView的视图
            boolean needRefreshView = false;
            if (user == null) {
                //注销了
                if (mAdapter == null) return;
                for (Article item : mAdapter.getData()) {
                    //注销了登陆   所以全部取消收藏
                    if (item.isCollect()) {
                        item.setCollect(false);
                        needRefreshView = true;
                    }
                }
            } else {
                //登陆了
                if (user.collectIds != null) {
                    int[] ids = user.collectIds;
                    for (int id : ids) {
                        for (Article item : mAdapter.getData()) {
                            if (item.getId() == id && !item.isCollect()) {
                                item.setCollect(true);
                                needRefreshView = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (needRefreshView) {
                mAdapter.notifyDataSetChanged();
            }
        };
        addLogInObserver(mUserObserver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeLogInObserver(mUserObserver);
    }

    @Override
    protected void initView() {
        super.initView();

        if (getActivity() == null) return;

        if (mBannerList != null) updateBanner(mBannerList);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        if (mAdapter == null) {
            mAdapter = new HomeAdapter();

            //初始化数据
            mPresenter.loadBanner();
            mPresenter.loadData(mPage);

            mAdapter.bindToRecyclerView(mRecyclerView);
            mAdapter.setPreLoadNumber(5);
            mAdapter.setOnLoadMoreListener(() -> {
                Log.e(TAG, "load more -> " + mPage);
                mSwipeRefreshLayout.setEnabled(false);
                mPresenter.loadData(mPage);
            }, mRecyclerView);

            mAdapter.setOnItemClickListener((adapter, view, position) -> {
                Article article = mAdapter.getItem(position);
                if (article != null && getActivity() != null) {
                    HtmlActivity.openUrl(getActivity(), article.getLink());
                }
            });

            mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                Article item = (Article) adapter.getItem(position);
                if (item == null) return;
                if (item.isCollect()) {
                    mPresenter.unCollectArticle(item.getId());
                } else {
                    mPresenter.collectArticle(item.getId());
                }
            });
        } else {
            //视图销毁重建  由于adapter不能被多次绑定 所以先用反射清空绑定值
            try {
                Field f = BaseQuickAdapter.class.getDeclaredField("mRecyclerView");
                f.setAccessible(true);
                f.set(mAdapter, null);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }

            mAdapter.bindToRecyclerView(mRecyclerView);
            //在销毁重建后需要通知更新视图
            mAdapter.notifyDataSetChanged();
        }

        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            mPage = 0;
            mPresenter.loadData(mPage);
            mAdapter.setEnableLoadMore(false);
        });

        setRetainInstance(true);
    }

    @Override
    protected HomeContract.IPresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_LOGIN:
                if (resultCode != Activity.RESULT_OK) return;
                //TODO 是否需要自动执行登陆之前的操作
                break;
            case REQUEST_CODE_COLLECT:
                if (resultCode != Activity.RESULT_OK) return;

                //解析intent data
                List<Integer> collectList = CollectActivity.getUnCollectIdList(data);
                if (collectList == null) return;

                //遍历列表id取消收藏
                for (int id : collectList) {
                    int index = findArticleIndexById(id);
                    if (index < 0) return;
                    Article article = mAdapter.getItem(index);
                    if (article == null) return;
                    article.setCollect(false);
                    mAdapter.notifyItemChanged(index);
                }
                break;
        }
    }

    @Override
    public void onTabReselect() {
        //如果RecyclerView已经滑动到顶部
        if (!mRecyclerView.canScrollVertically(-1)) {
            scrollBannerToTop();
            return;
        }

        LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        //如果当前位置超过一个值就先跳到某个值再滚动到起点
        if (llm != null && llm.findFirstVisibleItemPosition() > 30) {
            llm.scrollToPosition(30);
        }

        mRecyclerView.smoothScrollToPosition(0);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (newState != RecyclerView.SCROLL_STATE_IDLE) return;
                //移除这个临时的监听器以免影响其他操作
                mRecyclerView.removeOnScrollListener(this);
                //如果还能往上滑动  说明不在停在顶端  直接返回不处理
                if (mRecyclerView.canScrollVertically(-1)) return;
                //滑动到了顶端  再将轮播控件滑动到顶端
                scrollBannerToTop();
            }
        });
    }

    private void scrollBannerToTop() {
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams()).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            int topAndBottomOffset = appBarLayoutBehavior.getTopAndBottomOffset();
            if (topAndBottomOffset != 0) {
                appBarLayoutBehavior.setTopAndBottomOffset(0);
            }
        }
    }

    @Override
    public void showBanner(@Nullable List<Banner> data) {
        mBannerList = data;
        if (data == null) {
            showToast("加载轮播信息失败");
            mCyclicViewPager.setOnClickListener(v -> mPresenter.loadBanner());
            return;
        } else {
            mCyclicViewPager.setOnClickListener(null);
        }

        updateBanner(data);
    }

    private void updateBanner(@NonNull List<Banner> data) {
        final List<CyclicViewPager.Item> items = new ArrayList<>(data.size());
        CyclicViewPager.Item item;
        for (Banner banner : data) {
            item = new CyclicViewPager.Item();
            item.setTitle(banner.getTitle());
            item.setImageUrl(banner.getImagePath());
            item.setClickUrl(banner.getUrl());
            items.add(item);
        }

        mCyclicViewPager.setNewData(items);
        mCyclicViewPager.setOnItemClickListener(position -> {
            if (getActivity() != null)
                HtmlActivity.openUrl(getActivity(), items.get(position).getClickUrl());
        });
    }

    @Override
    public void showData(@Nullable MainData<Article> data) {
        mSwipeRefreshLayout.setEnabled(true);
        mAdapter.setEnableLoadMore(true);
        if (mSwipeRefreshLayout.isRefreshing())
            mSwipeRefreshLayout.setRefreshing(false);
        if (data == null) {
            if (mAdapter.isLoading()) {
                mAdapter.loadMoreFail();
            } else {
                showToast(R.string.refresh_failed);
            }
        } else {
            if (mPage == 0) mAdapter.getData().clear();
            mPage++;//加载成功后页码+1
            List<Article> articles = data.getData();
            if (articles != null) {
                mAdapter.addData(articles);
            }

            if (mAdapter.isLoading()) {
                if (data.isDataLoadOver()) {
                    mAdapter.loadMoreEnd();
                } else {
                    mAdapter.loadMoreComplete();
                }
            }
        }
    }

    @Override
    public void showCollectResult(int id, boolean result) {
        showToast(result ? R.string.collect_success : R.string.collect_failed);
        int index = findArticleIndexById(id);
        if (index < 0) return;
        Article article = mAdapter.getItem(index);
        if (article == null) return;
        article.setCollect(result);
        mAdapter.notifyItemChanged(index);
    }

    @Override
    public void showUnCollectResult(int id, boolean result) {
        showToast(result ? R.string.un_collect_success : R.string.un_collect_failed);
        int index = findArticleIndexById(id);
        if (index < 0) return;
        Article article = mAdapter.getItem(index);
        if (article == null) return;
        article.setCollect(!result);
        mAdapter.notifyItemChanged(index);
    }

    @Override
    public void needLogin() {
        startActivityForResult(new Intent(getActivity(), LoginActivity.class), REQUEST_CODE_LOGIN);
    }

    /**
     * 通过<code>id</code>查找数据在adapter中的位置
     *
     * @param id 需要查找的id
     * @return 如果查找到匹配的id值, 返回该对象在adapter中的位置;
     * 否则返回-1.
     */
    private int findArticleIndexById(int id) {
        Article article;
        List<Article> data = mAdapter.getData();
        for (int i = 0, size = data.size(); i < size; i++) {
            article = data.get(i);
            if (article.getId() == id) {
                return i;
            }
        }
        return -1;
    }
}
